<template>
  <!-- 合同信息 -->
  <div>
    <div class="middle-box">
      <span class="title"> 合同信息 </span>
    </div>
    <div class="btn_asset">
      <span class="btn_left">
        <el-button type="primary" @click="NewData"> 新增 </el-button>
        <el-button type="primary" @click="pushNewData"> 中止 </el-button>
        <el-button @click="batchDelete"> 删除 </el-button>
      </span>
      <span class="btn_right">
        <el-button size="small">
          <el-icon style="margin-right: 2px; margin-bottom: 2px"
            ><RefreshRight /></el-icon
          >刷新
        </el-button>
      </span>
    </div>
    <el-table
      max-height="450"
      stripe
      border
      size="small"
      :data="state.tableData.data"
      :cell-class-name="tableCellClassName"
      v-loading="state.tableData.loading"
      @cell-click="cellClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="50" />
      <el-table-column align="center" label="合同编号">
        <template #default="scope">
          <div
            v-if="
              scope.row.index === state.rowIndex &&
              scope.column.index === state.columnIndex
            "
          >
            <selectDown
              v-model:modelData="scope.row.contractNo"
              placeholder="请输入后搜索"
              urlType="currency"
            >
            </selectDown>
          </div>
          <span v-else>
            {{ scope.row.contractNo }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同类型">
        <template #default="scope">
          <div
            v-if="
              scope.row.index === state.rowIndex &&
              scope.column.index === state.columnIndex
            "
          >
            <!-- <el-input v-model="scope.row.contractType" size="small"> </el-input> -->
            <el-select
              v-model="scope.row.contractType"
              placeholder="请选择"
              filterable
              clearable
              size="small"
            >
              <el-option
                v-for="item in state.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <span v-else>
            {{ scope.row.contractType }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同期限" width="430">
        <template #default="scope">
          <div
            v-if="
              scope.row.index === state.rowIndex &&
              scope.column.index === state.columnIndex
            "
          >
            <el-date-picker
              v-model="scope.row.contractTerm"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :default-time="defaultTime1"
            />
          </div>
          <span v-else>
            {{ scope.row.contractTerm }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="到期提醒">
        <template #default="scope">
          <div
            v-if="
              scope.row.index === state.rowIndex &&
              scope.column.index === state.columnIndex
            "
          >
            <el-input
              v-model="scope.row.expirationReminder"
              placeholder="请输入"
              clearable
            >
              <template #prepend>到期前</template>
              <template #append>天</template>
            </el-input>
          </div>
          <span v-else>
            {{ scope.row.expirationReminder }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="中止时间">
        <template #default="scope">
          <div
            v-if="
              scope.row.index === state.rowIndex &&
              scope.column.index === state.columnIndex
            "
          >
            <el-input v-model="scope.row.stopTime" size="small" clearable>
            </el-input>
          </div>
          <span v-else>
            {{ scope.row.stopTime }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="执行状态">
        <template #default="scope">
          <div
            v-if="
              scope.row.index === state.rowIndex &&
              scope.column.index === state.columnIndex
            "
          >
            <!-- <el-input v-model="scope.row.excuteState" size="small" clearable></el-input> -->
            <el-select
              v-model="scope.row.excuteState"
              placeholder="请选择"
              filterable
              clearable
              size="small"
            >
              <el-option
                v-for="item in state.executeStateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </div>
          <span v-else>
            {{ scope.row.excuteState }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建合同信息 -->
    <el-dialog
      title="合同信息"
      v-model="state.dialogData.create_contract_show"
      width="448px"
    >
      <el-form
        :model="state.formData"
        :rules="state.formRules"
        label-suffix=":"
        label-width="80px"
        ref="form"
      >
        <el-row>
          <el-col>
            <el-form-item label="合同编号" prop="contractNo">
              <el-input
                v-model="state.formData.contractNo"
                fit-input-width
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="合同类型" prop="radio">
              <el-radio-group v-model="state.formData.radio">
                <el-radio :value="0">收款</el-radio>
                <el-radio :value="1">付款</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="合同期限" prop="contractTerm">
              <el-date-picker
                v-model="state.formData.contractTerm"
                type="datetimerange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                :default-time="defaultTime1"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="到期提醒" prop="expirationReminder">
              <el-input
                v-model="state.formData.expirationReminder"
                placeholder="请输入"
              >
                <template #prepend>到期前</template>
                <template #append>天</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="中止时间" prop="stopTime">
              <el-date-picker
                v-model="state.formData.stopTime"
                type="datetime"
                placeholder="请选择"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="执行状态" prop="excuteState">
              <el-select
                v-model="state.formData.excuteState"
                placeholder="请选择"
                fit-input-width
              >
                <el-option
                  v-for="item in state.options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel" type="default" size="small"
            >取消</el-button
          >
          <el-button
            type="primary"
            size="small"
            style="background: #5d9df5"
            @click="next"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  defineProps,
  defineEmits,
  computed,
  watch,
  toRaw,
} from "vue";
import selectDown from "./selectDown.vue";
import { ElMessageBox, ElMessage } from "element-plus";
// import request from "@/public/request";
import { useRoute, useRouter } from "vue-router";

const Route = useRoute();
const Router = useRouter();

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:show"]);

const inShow = computed({
  get() {
    return this.show;
  },
  set(value) {
    this.$emit("update:show", value);
  },
});
const state = reactive({
  rowIndex: -1, //行索引
  columnIndex: -1, //列索引

  btnLoading: false,
  // 表格数据
  tableData: {
    data: [
      {
        id: 1,
        // 合同编号
        contractNo: "111333",
        // 合同类型
        contractType: "收款",
        // 合同期限
        contractTerm: "",
        // 到期提醒
        expirationReminder: 5,
        // 中止时间
        stopTime: "2024-8-31",
        // 执行状态
        excuteState: "有效",
      },
      {
        id: 2,
        // 合同编号
        contractNo: "222333",
        // 合同类型
        contractType: "付款",
        // 合同期限
        contractTerm: "",
        // 到期提醒
        expirationReminder: 5,
        // 中止时间
        stopTime: "2024-8-31",
        // 执行状态
        excuteState: "有效",
      },
    ],
    radio: 1,
    loading: false,
  },
  copyData: [],
  formData: {
    // 合同编号
    contractNo: "",
    // 合同类型
    contractType: "",
    radio: 1,
    // 合同期限
    contractTerm: "",
    // 到期提醒
    expirationReminder: "",
    // 中止时间
    stopTime: "",
    // 执行状态
    excuteState: "",
  },
  formRules: {
    contractNo: [
      { required: true, message: "请输入合同编号", trigger: "blur" },
    ],
  },
  selectData: [],
  // 将表格选中的数据放入数组中
  tableSelect: [],
  dialogData: {
    create_contract_show: false,
  },
  options: [
    {
      value: "收款",
      label: "收款",
    },
    {
      value: "付款",
      label: "付款",
    },
  ],
  executeStateOptions: [
    {
      value: "有效",
      label: "有效",
    },
    {
      value: "中止",
      label: "中止",
    },
  ],
});

const handleSelectionChange = (val) => {
  let arr = [];
  for (let item of val) {
    let ret = toRaw(item);
    if (ret !== undefined) {
      arr.push(ret);
    }
  }
  state.tableSelect = arr;
};
// 批量删除点击事件
const batchDelete = () => {
  if (state.tableSelect.length > 0) {
    for (let i = state.tableSelect.length - 1; i >= 0; i--) {
      let deleteIndex = state.tableData.data.findIndex(
        (t) => t == state.tableSelect[i]
      );
      console.log("deleteIndex", deleteIndex);
      if (deleteIndex > -1) {
        state.tableData.data.splice(deleteIndex, 1);
      }
    }
  } else {
    this.$message.error("请先选择");
  }
};
const form = ref();
// 保存按钮点击事件
const next = async () => {
  await form.value.validate();
  state.dialogData.create_contract_show = false;
};

const handleClose = (done) => {
  done();
};
const tableCellClassName = ({ row, column, rowIndex, columnIndex }) => {
  column.index = columnIndex;
  row.index = rowIndex;
};
const cellClick = (row, column, cell, event) => {
  state.rowIndex = row.index;
  state.columnIndex = column.index;
};
// const handleSelectionChange = (selection) => {
//   state.selectData = selection;
// };
// const initData = () => {
//   if (!Route.query.entId) {
//     return;
//   }
//   state.tableData.loading = true;
//   request
//     .get("/api/buenterprisebank/query", {
//       EntId: Route.query.entId,
//     })
//     .then((res) => {
//       state.tableData.data = res;
//       state.copyData = res;
//     })
//     .finally(() => (state.tableData.loading = false));
// };
const pushNewData = () => {
  state.tableData.data.push({
    entId: Route.query.entId,
    currency: "",
    accountName: "",
    bankAccount: "",
    bankName: "",
    memo: "",
  });
};
const NewData = () => {
  state.dialogData.create_contract_show = true;
};
const cancel = () => {
  state.dialogData.create_contract_show = false;
  state.formData = {
    contractNo: "",
    contractType: "",
    radio: 1,
    contractTerm: "",
    expirationReminder: "",
    stopTime: "",
    excuteState: "",
  };
  form.value.clearValidate();
};
// const deleteData = () => {
//   let newArray = [];
//   state.tableData.data.forEach((t) => {
//     if (!state.selectData.find((item) => t == item)) {
//       newArray.push(t);
//     }
//   });
//   state.tableData.data = newArray;
// };

// const validData = () => {
//   for (let i of state.tableData.data) {
//     for (let j of Object.keys(i)) {
//       if (
//         j == "currency" ||
//         j == "accountName" ||
//         j == "bankAccount" ||
//         j == "bankName" ||
//         j == "entId"
//       ) {
//         if (!i[j]) {
//           return false;
//         }
//       } else {
//         continue;
//       }
//     }
//   }
//   return true;
// };
// const save = () => {
//   if (state.tableData.data.length == 0) {
//     ElMessage.warning("表格中没有数据");
//     return;
//   }
//   if (validData()) {
//     let newFormData = JSON.parse(JSON.stringify(state.tableData.data));
//     newFormData.forEach((t) => {
//       delete t.index;
//     });
//     // 判断列表数据是否存在币种，收款户名，银行账号，开户账户是否有完全相同的数据
//     let hasSameObj = false;
//     for (let i = 0; i < newFormData.length; i++) {
//       hasSameObj = false;
//       let checkObj = newFormData[i];
//       for (let j = i + 1; j < newFormData.length; j++) {
//         let sigleObj = newFormData[j];
//         if (
//           checkObj.currency == sigleObj.currency &&
//           checkObj.accountName == sigleObj.accountName &&
//           checkObj.bankAccount == sigleObj.bankAccount &&
//           checkObj.bankName == sigleObj.bankName
//         ) {
//           hasSameObj = true;
//           break;
//         }
//       }
//       if (hasSameObj) {
//         break;
//       }
//     }
//     if (hasSameObj) {
//       ElMessage.warning("列表数据存在两条相同的数据");
//       return;
//     }
//     this.btnLoading = true;
//     request
//       .post("/api/buenterprisebank/save", {
//         entId: Route.query.entId,
//         bankList: newFormData,
//       })
//       .then((res) => {
//         if (res.status) {
//           ElMessage.success(res.message);
//         } else {
//           ElMessage.error(res.message);
//         }
//       })
//       .finally(() => (state.btnLoading = false));
//   } else {
//     ElMessage.warning("数据中存在币种、收款户名、银行账号、开户账号为空");
//   }
// };
onMounted(() => {
  // initData();
});
</script>

<style lang="scss" scoped>
.middle-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .title {
    border-left: 2px solid #5d9df5;
    padding-left: 4px;
    font-size: 16px;
    font-weight: 600;
  }
}
::v-deep .el-dialog {
  padding: 0 !important;
}
::v-deep .el-dialog__title {
  margin: 8px 0px 0px 16px;
}
::v-deep .el-form {
  width: 400px;
}
::v-deep .el-dialog__header {
  display: flex;
  align-items: center;
  height: 36px;
  border-bottom: 1px solid #dee1e6;
}
::v-deep .el-dialog__footer {
  height: 40px;
  display: flex;
  justify-content: center;
  border-top: 1px solid #dee1e6;
}
::v-deep .dialog-footer {
  height: 24px;
  margin-top: -8px;
}
::v-deep .el-form-item__content {
  height: 24px;
}
::v-deep .el-radio__label {
  margin-right: -19px;
}
::v-deep .el-dialog__body {
  padding-bottom: 0;
}
.btn_asset {
  margin: 8px 0;
  display: flex;
  justify-content: space-between;
}
</style>
